package zl_service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/goravel/framework/facades"
	"github.com/goravel/framework/support/carbon"
	"goravel/app/models"
	"io/ioutil"
	"net/http"
)

// 根据门诊部职工食堂超市测试
const (
	COMMODITY_URL = "/zl.open.api.dcms.spubranchcommodity.choose.v5/1.0.0/action"
)

type CommodityData struct {
	ErrorMsg  string            `json:"errorMsg"`  // 错误信息
	ErrorCode string            `json:"errorCode"` // 错误码
	Success   string            `json:"success"`   // 是否成功
	Data      CommodityPaginate `json:"data"`
}

type CommodityPaginate struct {
	Page         int                `json:"page"`
	PageSize     int                `json:"pageSize"`
	TotalRecords int                `json:"totalRecords"`
	List         []models.Commodity `json:"list"`
}
type CommodityService struct {
}

func (b *CommodityService) QueryCommodity(site models.Site) error {
	url := BASE_URL + COMMODITY_URL
	client := &http.Client{}
	data_type := "1" //	1:查门店/网店商品（必传门店编码）;2查商品库商品
	if site.ID == 1 {
		data_type = "2"
	}
	// 请求参数结构体，对应要发送的JSON数据格式
	requestBody := struct {
		AppKey     string `json:"appkey"`
		Signtime   string `json:"signtime"`
		Shopcode   string `json:"shopcode"`
		PageSize   int    `json:"pageSize"`
		Datatype   string `json:"datatype"`   //1:查门店/网店商品（必传门店编码）;2查商品库商品
		Branchcode string `json:"branchcode"` //门店编码
	}{
		AppKey:     site.Appkey,
		Signtime:   carbon.NewDateTime(carbon.Now()).Format("Y-m-d H:i:s"),
		PageSize:   5000,
		Shopcode:   site.Shopcode,
		Datatype:   data_type,
		Branchcode: site.Branchcode,
	}

	bodyBytes, _ := json.Marshal(requestBody)
	stringToSign := fmt.Sprintf("%s&appsecret=%s", string(bodyBytes), site.Appsecret)
	upperSign := ComputeMD5AndToUpper(stringToSign)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyBytes))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Request-Sign", upperSign)
	body, err := client.Do(req)
	if err != nil {
		return err
	}
	//将body
	res, err := ioutil.ReadAll(body.Body)
	db := facades.Orm().Query()
	fmt.Sprintf("%s", res)
	var resp CommodityData

	err = json.Unmarshal(res, &resp)
	for ind, item := range resp.Data.List {
		resp.Data.List[ind].SiteID = site.ID
		db.Model(&models.Commodity{}).UpdateOrCreate(&resp.Data.List[ind], models.Commodity{SiteID: site.ID, Barcode: item.Barcode, SkuCode: item.SkuCode}, resp.Data.List[ind])
	}
	return nil
}
